package TCP和UDP;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpEchoClient {
    private int port;
    private String serverIp;
    private int serverPort;
    private DatagramSocket socket;
    public UdpEchoClient(String serverIp, int serverPort) throws SocketException {
        this.serverIp = serverIp;
        this.serverPort = serverPort;
        //让系统自动分配一个端口，不在手动进行分配
        socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动！");
        Scanner scanner = new Scanner(System.in);
        while(true) {
            //1.从控制台读取数据，作为请求
            System.out.print("-> ");
            String request = scanner.nextLine();
            //2.把请求构造成DatagramPacket对象，发送给服务器
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(serverIp), serverPort);
            socket.send(requestPacket);
            //3.尝试读取服务器发回的响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //4.把响应转换成String，打印出来
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            System.out.println(response);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient udpEchoClient = new UdpEchoClient("127.0.0.1",8080);
        udpEchoClient.start();
    }
}
